library(eliot)
library(Rcpp)
library(inline)
load(file='Data/CitationAndVoteData.RData')

# Unify Case Name IDs, and expand vote matrix to all cases with at least one citation #

AllCaseNames <- sort(unique(c(levels(as.factor(citationData$case)),levels(as.factor(citationData$precedent)))))
CitingCaseNames <- factor(citationData$case,levels= AllCaseNames)
CitedCaseNames <- factor(citationData$precedent,levels= AllCaseNames)
VoteCaseNames <- factor(rownames(voteMatrix),levels= AllCaseNames)

N <- dim(voteMatrix)[2]
M <- length(AllCaseNames)
A <- matrix(0,M,M)
Y <- matrix(NA,M,N)
colnames(Y) <- colnames(voteMatrix)

newVoteDetails <- voteDetails[0,]
for (k in 1:7) newVoteDetails[1,k] <- NA
newVoteDetails <- newVoteDetails[rep(1,M),]

for (j in 1:M){
	citationEntries <- which(as.numeric(CitingCaseNames) == j)
	if (length(citationEntries > 0)){
		A[j,as.numeric(CitedCaseNames[citationEntries])] <- citationData$citations[citationEntries]	
		}
	voteEntry <- which(as.numeric(VoteCaseNames) == j)	
	if (length(voteEntry > 0)){
		Y[j,] <- voteMatrix[voteEntry,]
		newVoteDetails[j,] <- voteDetails[voteEntry,]
		}
	}
	
voteDetails <- newVoteDetails	
	
hasvotedata <- rowMeans(is.na(Y)) < 1	
Y <- Y[hasvotedata,]
A <- A[hasvotedata,hasvotedata]
FinalCaseNames <- as.character(AllCaseNames[hasvotedata])
voteDetails <- voteDetails[hasvotedata,]
hasvotedata <- colMeans(is.na(Y)) < 1	
Y <- Y[,hasvotedata]	

M <- dim(Y)[1]
hascitedata <- rep(TRUE,M)
for (j in 1:M){	
	tempsum <- sum(A[j,])
	if (tempsum > 0) {
		A[j,] <- A[j,]/tempsum	
	} else {
		hascitedata[j] <- FALSE
	}
	if (sum(A[,j]) > 0) hascitedata[j] <- TRUE
}

Y <- Y[hascitedata,]
A <- A[hascitedata, hascitedata]
FinalCaseNames <- FinalCaseNames[hascitedata]
voteDetails <- voteDetails[hascitedata,]

save(voteDetails,Y,A,file=paste("Output/VoteDetailsForFittedSubset.Rdata",sep=""))

N <- dim(Y)[2]
M <- dim(Y)[1]

## Reflect Adjacency Matrix ##
gc()	
A <- A + t(A)	
gc()	
	
	
	
## Fit Model ##	

burn <- 1000
mcmc <- 1000
thin <- 20

carirt.out <- CARIRT(A,Y,IRT.polarity=-1,burn.iter=burn,mcmc.iter=mcmc,thin.iter=thin,store.alpha=TRUE,store.beta=TRUE,store.lambda=TRUE, store.average.pref=TRUE,store.latent.pref=TRUE,store.expected.pref=TRUE)

save(carirt.out,file=paste("Output/CARIRTSavedOutput.Rdata",sep=""))
